﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Lead2012.Models;
using Lead2012.ViewModels;
using Lead2012.Helpers;
using Lead2012.Business;
using System.Data.SqlClient;
using System.Data;

namespace Lead2012.Repository
{
    public class MilestoneManagementRepository : BaseManagementRepository
    {
        // Create an instance of entities framework
        Lead2012Entities entities = new Lead2012Entities();

        public void GetModel(MilestoneViewModel model, int sourceId, int userId)
        {
            model.ReportList = GetAllMilestoneReport(sourceId, userId, model.FromDate, model.ToDate);

            // Build common function
            model.UserFilter = GetAllUsers();
            model.UserFilter.Insert(0, new ItemFilter() { ID = "0", ItemName = "Tất cả người dùng" });
            model.SourceFilter = GetLeadSource();
            model.RangeFilter = GetRangeFilter();

            return;
        }

        public void GetModel(MilestoneViewModel model, string keywords, string sortBy, string sortOrder, int pageIndex, int pageSize)
        {
            int counts = 0;
            model.ItemList = GetAllMilestone(keywords, sortBy, sortOrder, pageIndex, pageSize, ref counts);            

            // Calculate paging
            if (counts > 0)
            {
                model.TotalPage = (counts % pageSize == 0) ? counts / pageSize : (counts / pageSize + 1);
                model.TotalRecord = counts;
                model.PageIndex = pageIndex;
                model.PageSize = pageSize;
            }
        }
        
        public void GetModel(MilestoneViewModel model, int id)
        {
            model.MilestoneInfo = GetSingleBy(id);
            model.MilestoneList = GetAllMilestone();
        }

        #region #Common

        public List<MilestoneItem> GetAllMilestone(string keywords, string sortBy, string sortOrder, int page, int take, ref int counts)
        {
            List<MilestoneItem> list = new List<MilestoneItem>();

            // Get milestone / actions
            
            var items = new MilestoneRepository().GetAll();
            
            // Add to list
            foreach (var item in items)
            {
                MilestoneItem model = new MilestoneItem();
                model.Id = item.Id;
                model.Title = item.Title;
                model.IsCustom = item.IsCustom;
                model.OrderId = item.OrderId;
                model.IsEnabled = item.IsEnabled;
                list.Add(model);
            }
           

            if (!string.IsNullOrEmpty(keywords))
            {
                list = list.Where(c => c.Title.ToLower().Contains(keywords.ToLower())).ToList();
            }

            counts = list.Count;

            
            // Add item to list
            switch (sortBy)
            {
                case "Title":
                    {
                        if (sortOrder == "asc")
                          list =  list.OrderBy(c => c.Title).Skip((page - 1) * take).Take(take).ToList();
                        else
                          list =  list.OrderByDescending(c => c.Title).Skip((page - 1) * take).Take(take).ToList();

                        break;
                    }
                
                
                default:
                    {
                        if (sortOrder == "asc")
                            list = list.OrderBy(c => c.Id).Skip((page - 1) * take).Take(take).ToList();
                        else
                            list = list.OrderByDescending(c => c.Id).Skip((page - 1) * take).Take(take).ToList();

                        break;
                    }
            }
            
            return list;
        }
        public int GetOrderId()
        {
            List<MilestoneItem> list = new List<MilestoneItem>();
            int OId = 0;
            // Get Status
            var items = new MilestoneRepository().GetAll();
            OId = items.Max(obj => obj.OrderId)+1;
            return OId;

        }
        public List<ItemFilter> GetAllMilestone()
        {
            List<ItemFilter> list = new List<ItemFilter>();

            var items = (from c in entities.Milestones select c).ToList();

            foreach (var item in items)
            {
                ItemFilter model = new ItemFilter();
                model.ID = item.Id.ToString();
                model.ItemName = item.Title;
                list.Add(model);
            }

            return list;
        }

        public MilestoneItem GetSingleBy(int id)
        {
            MilestoneItem model = new MilestoneItem();

            var item = (from c in entities.Milestones where c.Id == id select c).FirstOrDefault();
            if (item != null)
            {
                model.Id = item.Id;
                model.Title = item.Title;
                model.IsCustom = item.IsCustom;
                model.IsEnabled = item.IsEnabled;
                model.OrderId = item.OrderId;

           }

            return model;
        }
        #endregion

        #region Private method
        private List<MilestoneReportItem> GetAllMilestoneReport(int sourceId, int userId, DateTime startDate, DateTime endDate)
        {
            List<MilestoneReportItem> list = new List<MilestoneReportItem>();
            
            // Get all milestone info here
            // Params
            SqlParameter paramSource = new SqlParameter("@SourceId", DbType.Int32);
            paramSource.Value = sourceId;

            SqlParameter paramStart = new SqlParameter("@StartDate", DbType.DateTime);
            paramStart.Value = startDate;

            SqlParameter paramEnd = new SqlParameter("@EndDate", DbType.DateTime);
            paramEnd.Value = endDate;

            // Execute a query
            using (SqlDataReader item = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringProfile, CommandType.StoredProcedure, "GetReportByMilestone", paramSource, paramStart, paramEnd))
            {
                while (item.Read())
                {
                    MilestoneReportItem model = new MilestoneReportItem();
                    model.UserId = item.GetInt32(0);
                    model.Username = item.GetString(1);
                    model.NoneCount = item.GetInt32(2);
                    model.ContactCount = item.GetInt32(3);
                    model.RateCount = item.GetInt32(4);

                    // Calculate percent
                    int totalLeads = model.NoneCount + model.ContactCount + model.RateCount;

                    if (totalLeads > 0)
                    {
                        if (model.NoneCount > 0)
                            model.NonePercent = string.Format(@"{0} %", (((float)model.NoneCount / (float)totalLeads) * 100).ToString().Split('.')[0]);
                        else
                            model.NonePercent = "N/A";

                        if (model.ContactCount > 0)
                            model.ContactPercent = string.Format(@"{0} %", (((float)model.ContactCount / (float)totalLeads) * 100).ToString().Split('.')[0]);
                        else
                            model.ContactPercent = "N/A";

                        if (model.RateCount > 0)
                            model.RatePercent = string.Format(@"{0} %", (((float)model.RateCount / (float)totalLeads) * 100).ToString().Split('.')[0]);
                        else
                            model.RatePercent = "N/A";
                    }
                    else
                    {
                        model.NonePercent = "N/A";
                        model.ContactPercent = "N/A";
                        model.RatePercent = "N/A";
                    }

                    model.TotalLeads = totalLeads;

                    list.Add(model);
                }
            }

            if (userId > 0)
            {
                list = list.Where(c => c.UserId == userId).ToList();
            }

            return list;
        }

        #endregion
    }
}